package com.ofcoder.algorithmsamples.seata.dubbo.impl;

import com.ofcoder.algorithmsamples.seata.dubbo.api.AccountService;
import com.ofcoder.algorithmsamples.seata.dubbo.api.OrderService;
import com.ofcoder.algorithmsamples.seata.dubbo.api.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author: lyy
 * created in 2021/5/27
 */
public class OrderServiceImpl implements OrderService {
    private static final int PRICE = 50;
    private AccountService accountService;
    private StorageService storageService;
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void setStorageService(StorageService storageService) {
        this.storageService = storageService;
    }

    @GlobalTransactional
    @Override
    public void buy(String userId, String commodity, Integer count) {
        int money = PRICE * count;

        storageService.deduct(commodity, count);
        accountService.payment(userId, money);
        jdbcTemplate.update("insert into seata_order(user_id, commodity_code, count, money) VALUES(?, ?, ?, ?)", new Object[]{userId,commodity,count, money});
    }
}
